package com.midea.exam;

/**
 * @description：
 * @author: wangwl23
 * @create: 2021-08-17 20:28
 */


public class FindFirstWrongAns {

    public static void main(String[] args) {

        // String[] versions = new String[]{"1", "2", "3", "wrong1", "wrong2"};
        // String[] versions = new String[]{ "wrong1", "wrong2"};
        //String[] versions = new String[]{"hash1", "abcd2", "qoweioqhw3","doadjadj4", "wrong1ashdauhdu", "wrong2qweqweqwe"};
        String[] versions = new String[]{"1", "2", "3", "4", "5", "6", "wrong1", "wrong2", "wrong3", "wrong4"};
        System.out.println(findFirstWrong(versions));
    }

    /**
     * Return The first version of code that contains bugs and is wrong.
     *
     * @param versions total version of codes that are order by commit time.
     * @return The first wrong version of code.
     */
    public static String findFirstWrong(String[] versions) {
        int start = 0;
        int end = versions.length - 1;
        int middle = 0;
        while (start <= end) {
            //middle = (start + end) / 2;
            //防止int溢出的装逼写法
            middle = start + (end -start >>1);
            if (!checkRight(versions[middle])) {
                end = middle - 1;
            } else {
                start = middle + 1;
            }
        }
        return versions[middle];
    }

    /**
     * Check code which is right and contains no bugs.
     *
     * @param version The hash of code from one commit.
     * @return True if the version of code is Right. Otherwise return False.
     */
    public static boolean checkRight(String version) {

        // Just mock some time consuming check
        //doSomeTimeConsumingCheck();

        if (version.startsWith("wrong")) {
            return false;
        } else {
            return true;
        }
    }

    public static void doSomeTimeConsumingCheck() {
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

}
